#include "monthlyreportdetaildialog.h"
#include "ui_monthlyreportdetaildialog.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QDate>

MonthlyReportDetailDialog::MonthlyReportDetailDialog(int employeeId, const QString &toyName, const QString &processName, 
                                                   const QString &startDate, const QString &endDate, double pieceRate, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MonthlyReportDetailDialog),
    m_employeeId(employeeId),
    m_toyName(toyName),
    m_processName(processName),
    m_startDate(startDate),
    m_endDate(endDate),
    m_pieceRate(pieceRate)
{
    ui->setupUi(this);
    setupUI();
    loadDetailData();
}

MonthlyReportDetailDialog::~MonthlyReportDetailDialog()
{
    delete ui;
}

void MonthlyReportDetailDialog::setupUI()
{
    setWindowTitle(QString("生产详情 - %1 (%2)").arg(m_toyName).arg(m_processName.isEmpty() ? "无工序" : m_processName));
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    
    // 连接关闭按钮
    connect(ui->pushButtonClose, &QPushButton::clicked, this, &MonthlyReportDetailDialog::close);
}

void MonthlyReportDetailDialog::loadDetailData()
{
    // 清空表格
    ui->tableWidget->setRowCount(0);
    
    // 查询支持工序维度的生产详情
    QSqlQuery query;
    if (m_processName.isEmpty() || m_processName == "无工序") {
        // 查询旧版本表（无工序信息）
        query.prepare("SELECT p.date, p.quantity, t.piece_rate, (p.quantity * t.piece_rate) AS amount "
                      "FROM production p "
                      "JOIN toys t ON p.toy_id = t.id "
                      "WHERE p.employee_id = ? AND t.name = ? AND p.date BETWEEN ? AND ? "
                      "ORDER BY p.date");
        query.addBindValue(m_employeeId);
        query.addBindValue(m_toyName);
        query.addBindValue(m_startDate);
        query.addBindValue(m_endDate);
    } else {
        // 查询新版本表（包含工序信息）
        query.prepare("SELECT pv2.date, pv2.quantity, pv2.piece_rate, pv2.subtotal AS amount "
                      "FROM production_v2 pv2 "
                      "JOIN toys t ON pv2.toy_id = t.id "
                      "JOIN processes p ON pv2.process_id = p.id "
                      "WHERE pv2.employee_id = ? AND t.name = ? AND p.name = ? AND pv2.date BETWEEN ? AND ? "
                      "ORDER BY pv2.date");
        query.addBindValue(m_employeeId);
        query.addBindValue(m_toyName);
        query.addBindValue(m_processName);
        query.addBindValue(m_startDate);
        query.addBindValue(m_endDate);
    }
    
    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "查询生产详情失败: " + query.lastError().text());
        return;
    }
    
    // 填充表格
    double totalAmount = 0;
    int totalQuantity = 0;
    
    while (query.next()) {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);
        
        QString date = query.value(0).toString();
        int quantity = query.value(1).toInt();
        double price = query.value(2).toDouble();
        double amount = query.value(3).toDouble();
        
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(date));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(quantity)));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(price, 'f', 3)));
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(amount, 'f', 3)));
        
        totalAmount += amount;
        totalQuantity += quantity;
    }
    
    // 添加汇总行
    if (ui->tableWidget->rowCount() > 0) {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);
        
        QTableWidgetItem *summaryItem = new QTableWidgetItem("合计");
        summaryItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget->setItem(row, 0, summaryItem);
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(totalQuantity)));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem("--"));
        QTableWidgetItem *totalItem = new QTableWidgetItem(QString::number(totalAmount, 'f', 3));
        totalItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget->setItem(row, 3, totalItem);
    }
}